package com.base;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.alibaba.sdk.android.man.MANService;
import com.alibaba.sdk.android.man.MANServiceProvider;
import com.base.http.common.BaseHttpClient;
import com.base.http.common.HttpConfiguration;
import com.base.utils.DeviceInfo;
import com.base.utils.LogUtil;
import com.base.utils.MySharedPreferencesMgr;

/**
 * app基础类
 * Created by Android on 2017/3/7 0007.
 */

public class BaseApplication extends MultiDexApplication implements
        Thread.UncaughtExceptionHandler {

    public static String mDeviceId;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    public BaseApplication() {
        DeviceInfo.init(this);
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MySharedPreferencesMgr.init(this, "archstoday");
        initOneSdk();
        initHttp();
    }

    private void initOneSdk() {
        /* 【注意】建议您在Application中初始化MAN，以保证正常获取MANService*/
        // 获取MAN服务
        MANService manService = MANServiceProvider.getService();

        // 打开调试日志，线上版本建议关闭
        manService.getMANAnalytics().turnOnDebug();

        // MAN初始化方法之一，从AndroidManifest.xml中获取appKey和appSecret初始化
//        manService.getMANAnalytics().init(this, getApplicationContext());

        // MAN另一初始化方法，手动指定appKey和appSecret
        String appKey = "24651248";
        String appSecret = "cf2425b54440c51417a5eb1d39eab588";
        manService.getMANAnalytics().init(this, this, appKey, appSecret);

        // 若需要关闭 SDK 的自动异常捕获功能可进行如下操作,详见文档5.4
        //manService.getMANAnalytics().turnOffCrashReporter();

        // 通过此接口关闭页面自动打点功能，详见文档4.2
        //manService.getMANAnalytics().turnOffAutoPageTrack();

        // 设置渠道（用以标记该app的分发渠道名称），如果不关心可以不设置即不调用该接口，渠道设置将影响控制台【渠道分析】栏目的报表展现。如果文档3.3章节更能满足您渠道配置的需求，就不要调用此方法，按照3.3进行配置即可；
        manService.getMANAnalytics().setChannel("Reead Version");

        // 若AndroidManifest.xml 中的 android:versionName 不能满足需求，可在此指定
        // 若在上述两个地方均没有设置appversion，上报的字段默认为null
        manService.getMANAnalytics().setAppVersion(String.valueOf(getVerCode()));
    }

    /**
     * 获取设备id
     *
     * @param context
     * @return
     */
    public static String getDeviceID(Context context) {
        if (mDeviceId == null) {
            mDeviceId = DeviceInfo.getDeviceInfo(context);
            if (mDeviceId == null || mDeviceId.length() < 2) {
                //mDeviceId = MySharedPreference.getString("clientid", null);
                if (mDeviceId == null) {
                    mDeviceId = DeviceInfo.getUUID();
                    //MySharedPreferencesMgr.setString("clientid", mDeviceId);
                }
            }
        }
        return mDeviceId;
    }

    /**
     * 得到系统版本号
     *
     * @return
     */
    public int getVerCode() {
        int verCode = -1;
        try {
            verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verCode;
    }

    /**
     * 得到系统版本名称
     *
     * @return
     */
    public String getVerName() {
        String verName = "";
        try {
            verName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verName;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
        if (!treatErr(e) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(t, e);
        } else {
            quit();
        }
    }

    public boolean treatErr(Throwable ex) {
        return false;
    }

    /**
     * 控制应用退出操作
     */
    @SuppressLint("NewApi")
    public void quit() {
        int version = android.os.Build.VERSION.SDK_INT;
        if (version <= 7) {
            System.out.println("   version  < 7");
            ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            manager.restartPackage(getPackageName());
        } else {
            ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            manager.killBackgroundProcesses(getPackageName());
        }
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
    }

    /**
     * 初始化网络配置传入
     */
    void initHttp() {
        LogUtil.log_e("HX", "======== 初始化网络配置 ========");
        HttpConfiguration.Builder configuration = new HttpConfiguration.Builder(getApplicationContext());
        configuration.connectTimeout(2000);
        configuration.retryOnConnectionFailure(true);
        configuration.readTimeout(2000);
        configuration.writeTimeout(2000);
        configuration.diskCacheSize(1000 * 1024);
        configuration.diskCacheDir(getCacheDir());
        BaseHttpClient.getBaseClient().init(configuration.build());
    }
}
